package cn.com.fattiger.framework.cyclicbrrier;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 
 * @author fattiger.xiaoyang
 * @date 2016/04/05
 */
public class CyclicBarrierDemo {

	public static void main(String[] args) {
		final int COUNT_NUM = 3;
		final CyclicBarrier brrier = new CyclicBarrier(COUNT_NUM);
		for (int i = 0; i < COUNT_NUM; i++) {
			new Thread(new CountHandler(brrier)).start();
		}
//		try {
//            Thread.sleep(25000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
		System.out.println("CyclicBarrier重用");
		for (int i = 0; i < COUNT_NUM; i++) {
			new Thread(new CountHandler(brrier)).start();
		}
	}
}

class CountHandler implements Runnable {
	private CyclicBarrier brrier;

	public CountHandler(CyclicBarrier brrier) {
		this.brrier = brrier;
	}

	@Override
	public void run() {
		System.out.println("线程" + Thread.currentThread().getName() + "工作。");
		try {
			Thread.sleep(5000); // 以睡眠来模拟写入数据操作
			System.out.println("线程" + Thread.currentThread().getName() + "工作完毕等待3个子线程执行完毕...");
			brrier.await();
		} catch (InterruptedException | BrokenBarrierException e) {
			e.printStackTrace();
		}
		System.out.println("3个子线程已经执行完毕");
		System.out.println("继续执行主线程");
	}

}
